using System;
using System.Collections.Generic;
using System.Linq;
using WatiN.Core;
using WatiN.Core.Constraints;
using YatFram.Browser.CssSelector;

namespace YatFram.Browser.Watin
{
    public class WatinBrowser : IBrowser
    {
        private readonly IE ie;

        public WatinBrowser(string url)
        {
            ie = new IE(url);
        }

        public void GoTo(string url)
        {
            ie.GoTo(url);
        }
       
        public string Dump()
        {
            return ie.Text;
        }

        public bool Exists
        {
            get { throw new NotImplementedException(); }
        }

//        public IEnumerable<IContainerElement> Find(string cssSelector)
//        {
//            return ie.FindElements(cssSelector).Select(element => (IContainerElement)new WatinContainerElement(element));
//        }

        public IEnumerable<IContainerElement> Find(CssSelectors selector)
        {
            return ie.ElementsOfType<Element>().Filter(selector.ToConstraint()).Select(e => (IContainerElement)new WatinContainerElement(e));
        }

        public InputElement FindTextBox(string cssSelector)
        {
            return new WatinTextBox(ie.TextField(ConstraintFor(cssSelector)));
        }

        public ISingleOption FindSelect(string cssSelector)
        {
            return new WatinSelectBox(ie.SelectList(ConstraintFor(cssSelector)));
        }

        public ISingleOption FindRadio(string name)
        {
            return new WatinRadioBox(ie.RadioButtons.Where(button => button.GetAttributeValue("name") == name));
        }

        public IMultipleOptions FindCheckbox(string name)
        {
            return new WatinCheckBox(ie.CheckBoxes.Where(box => box.GetAttributeValue("name") == name));
        }

        private Constraint ConstraintFor(string cssSelector)
        {
            return cssSelector.ToCssSelectors().Select(selector => selector.ToConstraint()).First();
        }

        public void Dispose()
        {
            ie.Close();
        }
    }
}